<template>
  <div>
    <div :id="charId" style="width: 100%; height: 250px;"></div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'EventChart',
  data () {
    return {
      search: null,
      charId: 'event-echarts',
      myChart: null
    }
  },
  watch: {
  },
  created () {
    // getServiceList().then(res => {
    //   console.log('getServiceList.call()', res)
    // })
    this.getSystosyslast()
  },
  methods: {

    /**
     * 初始化
     */
    init (search) {
      // 查询参数
      this.search = search
      this.getEventCount(this.search)
    },

    /**
     * 查询事件
     */
    getEventCount (result) {
      var params = {
        url: `elastic/${result.url}/_search`,
        query: {
          aggs: {
            event: {
              date_histogram: {
                field: 'timestamp',
                interval: result.step,
                format: 'yyyy-MM-dd HH:mm:ss',
                extended_bounds: {
                  'min': moment(result.date.start).utc().format('YYYY-MM-DD HH:mm:ss'),
                  'max': moment(result.date.end).utc().format('YYYY-MM-DD HH:mm:ss')
                }
              }
            }
          }
        }
      }
      // 获取数据
      esSearch(params).then((res) => {
        console.log(res)
        this.getEcharts(res)
      })
    },

    /**
     * 构建echarts图表
     */
    getEcharts (resource) {
      if (!resource.aggregations) return
      this.myChart = null
      this.myChart = echarts.init(document.getElementById(this.charId))
      var options = this.getEchartsOptions(resource)
      console.log(options, this.myChart)
      this.myChart.setOption(options, true)
    },

    /***
     * 组装echarts参数
     */
    getEchartsOptions (resource) {
      var buckets = resource.aggregations.event.buckets
      const options = {
        title: {},
        tooltip: {},
        legend: {
          show: false
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: 50,
          top: '10%'
        },
        dataZoom: [{
          type: 'inside'
        }, {
          type: 'inside'
        }],
        xAxis: {
          data: [],
          splitLine: {
            show: false
          }
        },
        yAxis: {
          splitLine: {
            show: false
          }
        },
        series: [
          {
            name: '销量',
            type: 'bar',
            data: []
          }
        ]
      }

      buckets.forEach(item => {
        options.xAxis.data.push(item.key_as_string)
        options.series[0].data.push(item.doc_count)
      })
      return options
    }
  }
}
</script>

<style lang="less" scoped>

</style>
